package com.lovezy.platform.core.base;

import com.lovezy.platform.core.exception.BaseRuntimeException;
import com.lovezy.platform.core.exception.DefaultErrorCode;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Created by jin on 2017/11/6.
 */
@RestControllerAdvice
public class CoreControllerAdvice {

    private final Log log = LogFactory.getLog(CoreControllerAdvice.class);

    @ExceptionHandler(BaseRuntimeException.class)
    public ResponseEntity<ErrorResponse> errorHandler(BaseRuntimeException e) {
        if (log.isDebugEnabled()) {
            log.debug("服务异常",e);
        }
//        ResponseStatus responseStatus = e.getClass().getAnnotation(ResponseStatus.class);
//        if (responseStatus != null) {
            return new ResponseEntity<>(new ErrorResponse(e.getErrorCode(), e.getErrorMsg()), HttpStatus.OK);
//        } else {
//            return new ResponseEntity<>(new ErrorResponse(e.getErrorCode(), e.getErrorMsg()), HttpStatus.INTERNAL_SERVER_ERROR);
//        }
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> defaultExceptionHandler(Exception e) {
        log.error("系统异常", e);
//        ResponseStatus responseStatus = e.getClass().getAnnotation(ResponseStatus.class);
//        if (responseStatus != null) {
//            return new ResponseEntity<>(new ErrorResponse(DefaultErrorCode.SERVICE_ERROR, e.getMessage()), responseStatus.value());
//        } else {
//            return new ResponseEntity<>(new ErrorResponse(DefaultErrorCode.SERVICE_ERROR,e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
//        }
        return new ResponseEntity<>(new ErrorResponse(DefaultErrorCode.SERVICE_ERROR,e.getMessage()), HttpStatus.OK);

    }


}
